<script setup>
import { computed, reactive, ref, toRaw } from "vue";
import { cloneDeep } from "lodash-es";
import { get, del, serverUrl, post, dalImg, patch } from "../../utils/request";
import { CheckOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons-vue";
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons-vue';
const dataSource = ref([]);
const isEnd = ref(false);
const hospital_url = ref("");
const num = ref(0);
const arr = ref([]);
const hospital_id = ref("");
const hospital = () => {
  get("/admin/hospitals").then((res) => {
    // console.log(res);
    dataSource.value = res.data.list.map((item, index) => ({
      key: item.id,
      sort: index + 1,
      address: item.address,
      content: item.content,
      id: item.id,
      name: item.name,
      desc: item.desc,
      image: dalImg(item.image),
      phone: item.phone,
      createdAt: new Date(item.createdAt).toLocaleString(),
      updatedAt: new Date(item.updatedAt).toLocaleString(),
    }));
  });
};
hospital();
const columns = [
  {
    title: "编号",
    dataIndex: "sort",
  },
  {
    title: "名称",
    dataIndex: "name",
  },
  {
    title: "图片",
    dataIndex: "image",
  },

  {
    title: "描述",
    dataIndex: "desc",
  },

  {
    title: "地址",
    dataIndex: "address",
  },
  {
    title: "电话",
    dataIndex: "phone",
  },
  {
    title: "创建时间",
    dataIndex: "createdAt",
  },
  {
    title: "更新时间",
    dataIndex: "updatedAt",
  },
  {
    title: "操作",
    dataIndex: "operation",
  },
];
const count = computed(() => dataSource.value.length + 1);
const editableData = reactive({});
// 点击修改
const edit = (key) => {
  editableData[key] = cloneDeep(
    dataSource.value.filter((item) => key === item.key)[0]
  );
};
const save = (key) => {
  Object.assign(
    dataSource.value.filter((item) => key === item.key)[0],
    editableData[key]
  );
  delete editableData[key];
};
// 点击删除
const onDelete = (key) => {
  console.log(key);
  del("/admin/hospitals/" + key).then((res) => {

    dataSource.value = dataSource.value.filter((item) => item.key !== key);
  })
}
// 点击新增
const handleAdd = () => {
  isEnd.value = !isEnd.value
  num.value = 1
  formState.value.name = ''
  formState.value.desc = ''
  hospital_url.value = ''
  formState.value.content = ''
  formState.value.naddressame = ''
  formState.value.phone = ''
};
const mod = (key) => {
  isEnd.value = !isEnd.value
  num.value = 2
  arr.value = dataSource.value.filter((item) => item.key == key);

  formState.value = {
    name: arr.value[0].name,
    desc: arr.value[0].desc,
    image: arr.value[0].image,
    content: arr.value[0].content,
    address: arr.value[0].address,
    phone: arr.value[0].phone,
  }
  hospital_id.value = key;
}
const formState = ref({
  name: '',
  desc: '',
  image: '',
  content: '',
  address: '',
  phone: '',
});

const onSubmit = () => {
  console.log('submit!', toRaw(formState));
  const data = {
    name: formState.value.name,
    desc: formState.value.desc,
    image: hospital_url.value,
    content: formState.value.content,
    address: formState.value.address,
    phone: formState.value.phone,
  }
  if (num.value == 1) {
    post("/admin/hospitals", data).then((res) => {
      hospital()
      dataSource.value.push(data);
      isEnd.value = false
    })
  } else if (num.value == 2) {
    const data = formState.value
    data.image = hospital_url.value
    patch("/admin/hospitals/" + hospital_id.value, data).then((res) => {
      isEnd.value = false
      hospital()
    })
  }
};
// 图片上传
import { message } from 'ant-design-vue';
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
const fileList = ref([]);
const loading = ref(false);
const imageUrl = ref('');
const handleChange = info => {
  if (info.file.status === 'uploading') {
    loading.value = true;
    return;
  }
  if (info.file.status === 'done') {
    // Get this url from response in real world.
    console.log(info.file.response.data);
    hospital_url.value = info.file.response.data;
    getBase64(info.file.originFileObj, base64Url => {
      imageUrl.value = base64Url;
      loading.value = false;
    });
  }
  if (info.file.status === 'error') {
    loading.value = false;
    message.error('upload error');
  }
};
const beforeUpload = file => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
};
const resetForm = () => {
  isEnd.value = false
}
const keyHandle = () => {
  const name = formState.value.name
  get('/admin/doctor_tags/' + name).then(res => {
    dataSource.value = dataSource.value.filter(item => {
      return item.name.indexOf(name) != -1
    });
  })
}
</script>

<template>
  <div class="admin">
    <a-button class="editable-add-btn" style="margin-bottom: 8px" @click="handleAdd">新增</a-button>

    <a-form-item label="名称">
      <a-input v-model:value="formState.name" @keyup.enter="keyHandle" style="width: 300px;" />
    </a-form-item>
    <a-table bordered :data-source="dataSource" :columns="columns">
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.dataIndex === 'name'">
          <div class="editable-cell">
            <div v-if="editableData[record.key]" class="editable-cell-input-wrapper">
              <a-input v-model:value="editableData[record.key].name" @pressEnter="save(record.key)" />
              <check-outlined class="editable-cell-icon-check" @click="save(record.key)" />
            </div>
            <div v-else class="editable-cell-text-wrapper">
              {{ text || " " }}
            </div>
          </div>
        </template>
        <template v-if="column.dataIndex === 'image'">
          <div class="editable-cell">
            <div v-if="editableData[record.key]" class="editable-cell-input-wrapper">
              <a-input v-model:value="editableData[record.key].image" @pressEnter="save(record.key)" />
              <check-outlined class="editable-cell-icon-check" @click="save(record.key)" />
            </div>
            <div v-else class="editable-cell-text-wrapper">
              <img :src="text" class="editable-cell-image" />
            </div>
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'operation'">
          <a-popconfirm v-if="dataSource.length" title="是否确认删除" @confirm="onDelete(record.key)">
            <a>
              <DeleteOutlined style="color: white; background-color: red; font-size: 20px; padding: 5px;" />
            </a>
          </a-popconfirm>
          <a>&emsp;
            <EditOutlined @click="mod(record.key)"
              style="color:white;background-color: rgb(12, 67, 229); font-size: 20px; padding: 5px;" />
          </a>
        </template>
      </template>
    </a-table>
    <!-- 表单 -->
    <div class="form" v-if="isEnd">
      <a-form ref="formRef" :model="formState" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol"
        style="width: 600px;">
        <a-form-item label="名称">
          <a-input v-model:value="formState.name" />
        </a-form-item>
        <a-form-item label="简介">
          <a-textarea :rows="3" v-model:value="formState.desc" />
        </a-form-item>
        <a-form-item label="地址">
          <a-input v-model:value="formState.address" />
        </a-form-item>
        <a-form-item label="电话">
          <a-input v-model:value="formState.phone" />
        </a-form-item>
        <a-upload v-model:file-list="fileList" name="file" list-type="picture-card" class="avatar-uploader"
          :show-upload-list="false" :action="serverUrl + '/common/upload'" :before-upload="beforeUpload"
          @change="handleChange">
          <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
          <div v-else>
            <loading-outlined v-if="loading"></loading-outlined>
            <plus-outlined v-else></plus-outlined>
            <div class="ant-upload-text">Upload</div>
          </div>
        </a-upload>
        <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
          <a-button type="primary" @click="onSubmit">确认</a-button>
          <a-button style="margin-left: 10px" @click="resetForm">取消</a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<style scoped>
.admin {
  height: 100%;
  overflow: auto;
}

.admin :deep(.ant-table-cell):nth-child(4) {
  width: 100%;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  overflow: hidden;
  line-height: 100px;
}

.admin :deep(.ant-table-cell):nth-child(1) {
  width: 5%
}

.admin :deep(.ant-table-cell):nth-child(2) {
  width: 10%
}

.admin :deep(.ant-table-cell):nth-child(3) {
  width: 10%;
}

.admin :deep(.ant-table-cell):nth-child(5) {
  width: 10%;
}

.admin :deep(.ant-table-cell):nth-child(6) {
  width: 10%;
}

.admin :deep(.ant-table-cell):nth-child(7) {
  width: 10%;
}

.admin :deep(.ant-table-cell):nth-child(8) {
  width: 10%;
}

.admin :deep(.ant-table-cell):nth-child(9) {
  width: 10%;
}

.form {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: gray;
  padding: 15px;
  z-index: 100;

}

img {
  width: 100px;
}

.editable-add-btn {
  background-color: rgb(17, 222, 212);
  color: white;
  margin-right: 20px;
}
</style>
